<script lang="ts" setup>
import { CourseItem, CourseItemDetail, CourseVideo, Course, StudyRecord, PlayingInfo } from "@/types/course";
import BjyPlayer from "./bjy-player.vue";
import { getOSSURL } from "@/utils/utils";
import { useUserStore } from "@/store/modules/user";
import * as CourseApi from "@/api/train/course";
import useBjyPlayer from "../useBjyPlayer";
import { onBeforeRouteLeave } from "vue-router";
import "@nutui/nutui/dist/packages/dialog/style";
import { showDialog, showToast } from "@nutui/nutui";

const userStore = useUserStore();

const props = defineProps<{
  coverUrl?: string;
  courseId: Course["id"];
  playingInfo: PlayingInfo | null;
  currentItemId: CourseItem["id"];
  itemsMap: Map<CourseItem["id"], CourseItem>;
  itemDetailMap: Map<CourseItem["id"], CourseItemDetail>;
}>();

// 播放器
const bjyPlayer = ref<typeof BjyPlayer | null>(null);
// 记录旧的课程id
const oldItemId = ref();
const oldCourseId = ref();

const playingSource = ref<{ vid: number; token: string; seek: number } | null>(null);
watch(
  () => props.playingInfo,
  async (val, old) => {
    if (old) {
      const player = bjyPlayer.value?.player;
      if (player) uploadStudyRecord(true, oldCourseId.value, oldItemId.value);
    }
    if (!props.playingInfo) playingSource.value = null;
    // 记录课程信息
    oldItemId.value = props.currentItemId;
    oldCourseId.value = props.courseId;
    console.log("new", oldCourseId.value, oldItemId.value);
    const { vid, videoId } = val!;
    const { data: token } = await CourseApi.getPlayerTokenByBjyVideoId(videoId);

    const item = props.itemsMap.get(props.currentItemId) as CourseItem | undefined;

    playingSource.value = { vid, token, seek: 0 };

    // window.scrollTo({ top: 0, behavior: "smooth" });

    if (item?.studyRecord?.studyProgress && item?.studyRecord?.studyProgress < 100) {
      showDialog({
        title: "提示",
        content: "是否跳转到上次学习的进度？",
        okText: "立即跳转",
        cancelText: "重新学习",
        onOk: () => {
          const player = bjyPlayer.value?.player;
          if (!player) return;
          playingSource.value.seek = (item.studyRecord!.studyProgress! / 100) * player.duration;
          player.seek((item.studyRecord!.studyProgress! / 100) * player.duration);
        },
        onClosed: () => {
          const player = bjyPlayer.value?.player;
          if (!player) return;
        },
      });
    }
  }
);

const playerOptions = useBjyPlayer({
  marqueeText: userStore.userInfo?.nickname || "",
  waterMarkUrl: getOSSURL("imgs/h5-others/数字微驾logo.jpg"),
  seek: 0,
});

const playNext = () => {
  // TODO: 下一个视频
  console.log("playNext");
};
const resetSeek = () => {
  console.log("resetSeek");
  bjyPlayer.value?.seek(0);
  bjyPlayer.value?.play();
  bjyPlayer.value?.visibleEndMask(false);
};
const replaceVideo = (video: CourseVideo) => {
  console.log("replaceVideo", video);
};

/** 上传视频学习进度 */
const uploadStudyRecord = (isSwitchVideo = false, oldCourseId = "", oldItemId = "") => {
  
  if (playingSource.value) {
    const player = bjyPlayer.value?.player;

    if (!player?.currentTime) return;

    console.log((player.currentTime / player.duration) * 100);
    CourseApi.updateStudyRecord({
      courseId: isSwitchVideo ? oldCourseId : props.courseId,
      itemId: isSwitchVideo ? oldItemId : props.currentItemId,
      studyProgress: (player.currentTime / player.duration) * 100,
    }).then((res) => {
      console.log("old");
      console.log("updateStudyRecord", res);
    });
  }
};

/** 页面退出前 */
onBeforeRouteLeave((to, from) => {
  uploadStudyRecord();
  playingSource.value = null;
});

/** 播放结束 */
const handleEnded = () => {
  console.log("handleEnded");
  uploadStudyRecord();
};
</script>

<template>
  <!-- 百家云 -->
  <bjy-player
    ref="bjyPlayer"
    v-if="playingSource"
    class="sticky top-0 z-10"
    :vid="playingSource.vid"
    :token="playingSource.token"
    :marquee="playerOptions.marquee"
    :seek="playingSource.seek"
    :menory="false"
    @replaceVideo="replaceVideo"
    @resetSeek="resetSeek"
    @playNext="playNext"
    @ended="handleEnded"
    :waterMark="playerOptions.waterMark"
  />

  <!-- 默认封面 -->
  <nut-image v-else-if="coverUrl" class="w-full" :src="getOSSURL(coverUrl)" fit="cover" show-loading />
  <!-- 默认封面 -->

  <!-- 骨架屏 -->
  <nut-skeleton v-else width="0px" height="0px" class="w-full h-50 bg-gray-2" animated />
</template>

<style>
.nut-dialog__content {
  font-size: 0.9rem;
}

.nut-button--small {
  font-size: var(--nut-button-small-font-size, var(--nut-font-size-1, 14px));
}
</style>
